
import store from '@/store'
import { Module, VuexModule, Mutation, Action, getModule } from 'vuex-module-decorators'
import request from '@/utils/request'
import asyncRouterMap from '@/router/generateRouter'
import _ from 'lodash'

@Module({
  name: 'userRole',
	store,
	dynamic: true,
  namespaced: true
})
export default class UserRole extends VuexModule {
  public role = []
	public routers = _.cloneDeep(asyncRouterMap)

  @Mutation
  SET_ROLE(data: []) {
    this.role = data
  }

	@Mutation
  SET_ROUTERS(data: []) {
    this.routers = data
  }

  @Action({ commit: 'SET_ROLE' })
  async getRole() {
		const option = {
			method: 'GET',
			data: {
				umId: 'feilong@tendcloud.com'
			}
		}
		const res = await request(`/reportservice/config/menus/FEILONG`, option)
		return new Promise((resolve) => {
			resolve(res.data.menuList)
		})
  }

	@Action({ commit: 'SET_ROUTERS' })
	generateRoutes() {
		const routes: any[] = []
		asyncRouterMap.forEach((value: { [key: string]: any }) => {
			this.role.forEach((val: { [key: string]: any }) => {
				if (val.path === value.path) {
					const item = _.cloneDeep(value)
					let children: any[] = []
					val.childrens.forEach((k: { [key: string]: any}) => {
						const filterData = value.children.filter((n: { [key: string]: any}) => {
							return k.path === n.path
						})
						children = children.concat(filterData)
					})
					if (children.length) {
						item.children = children
					} else {
						delete item.children
					}
					routes.push(item)
				}
			})
		})
		return routes
	}
}

export const UserRoleModule = getModule(UserRole)
